//
//  SubjectViewController.m
//  Double
//
//  Created by 袁庆秋 on 15/5/21.
//  Copyright (c) 2015年 袁庆秋. All rights reserved.
//

#import "SubjectViewController.h"
#import "RecommendViewController.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import "MJRefresh.h"
#import "SubjectCell.h"
#import "TopicModel.h"
#import "RankModel.h"
#import "TopicViewController.h"
#import "RankViewController.h"

@interface SubjectViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic, assign) NSInteger pageCount;


@end

@implementation SubjectViewController

- (void)dealloc
{
    [_topicArray release];
    [_collectView release];
    [_rankArray release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.topicArray = [NSMutableArray array];
        self.rankArray = [NSMutableArray array];
        self.pageCount = 100;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self startConnection];
    [self createCollectionView];
}

#pragma mark -
#pragma mark 数据请求
- (void)startConnection
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSString *str = @"http://manhua.haomee.cn/?m=List&ios=23&pad=0&last_id=0";
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *topic = [dic objectForKey:@"topic"];
        NSArray *rank = [dic objectForKey:@"rank"];
        for (NSDictionary *dic in topic) {
            TopicModel *model = [[TopicModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.topicArray addObject:model];
        }
        for (NSDictionary *dic in rank) {
            RankModel *model = [[RankModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.rankArray addObject:model];
        }
        [self.collectView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}






#pragma mark -
#pragma mark 创建collectionView
- (void)createCollectionView
{
    UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc] init];
    flow.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    self.collectView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, self.view.frame.size.height - 64) collectionViewLayout:flow];
    [self.collectView setBackgroundColor:[UIColor whiteColor]];
    [self.collectView registerClass:[SubjectCell class] forCellWithReuseIdentifier:@"cell"];
    self.collectView.delegate = self;
    self.collectView.dataSource = self;
    
    //上拉加载
    [self.collectView addLegendFooterWithRefreshingTarget:self refreshingAction:@selector(collectionViewLoad)];
    //下拉刷新
    [self.collectView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(collectionViewRefresh)];
    [self.view addSubview:self.collectView];
    [_collectView release];
}

//下拉刷新
- (void)collectionViewRefresh
{
    [self.topicArray removeAllObjects];
    [self.rankArray removeAllObjects];
    [self startConnection];
    [self.collectView reloadData];
    [self.collectView.header endRefreshing];
}
//上拉加载
- (void)collectionViewLoad
{
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    NSString *str = @"http://manhua.haomee.cn/?m=List&ios=23&pad=0&last_id=0";
    NSString *str = [NSString stringWithFormat:@"http://manhua.haomee.cn/?m=List&ios=23&pad=0&last_id=%ld", self.pageCount];
    [manager GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *topic = [dic objectForKey:@"topic"];
        NSArray *rank = [dic objectForKey:@"rank"];
        for (NSDictionary *dic in topic) {
            TopicModel *model = [[TopicModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.topicArray addObject:model];
        }
        for (NSDictionary *dic in rank) {
            RankModel *model = [[RankModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.rankArray addObject:model];
        }
        if (self.topicArray.count == 0) {
            [self.collectView removeFooter];
            return ;
        }
        self.pageCount += 1;
        [self.collectView.footer endRefreshing];
        [self.collectView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.collectView.footer endRefreshing];
    }];
}

#pragma mark -
#pragma mark 实现collectionView
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return (self.rankArray.count + self.topicArray.count);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(self.view.frame.size.width - 20, 200);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    SubjectCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    if (indexPath.item < 4) {
        RankModel *model = [self.rankArray objectAtIndex:indexPath.item];
        [cell.showImage sd_setImageWithURL:[NSURL URLWithString:model.cover] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
        cell.titleLabel.text = model.title;
    }
    if (indexPath.item >= 4) {
        TopicModel *model = [self.topicArray objectAtIndex:(indexPath.item - 4)];
        [cell.showImage sd_setImageWithURL:[NSURL URLWithString:model.pic] placeholderImage:[UIImage imageNamed:@"placeholder.jpg"] options:SDWebImageRetryFailed];
        cell.titleLabel.text = model.name;
    }
    
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.item < 4) {
        RankModel *model = [self.rankArray objectAtIndex:indexPath.item];
        RankViewController *rank = [[RankViewController alloc] init];
        rank.name = model.title;
        rank.myId = model.myId;
        [self.navigationController pushViewController:rank animated:YES];
    } else if (indexPath.item >= 4) {
        TopicModel *model = [self.topicArray objectAtIndex:(indexPath.item - 4)];
        TopicViewController *topic = [[TopicViewController alloc] init];
        topic.myId = model.myId;
        topic.name = model.name;
        [self.navigationController pushViewController:topic animated:YES];
    }
}


@end
